/**
 * Program  : LoadActivity.java
 * Author   : long
 * Create   : 2015年12月28日 上午10:13:58
 *
 * Copyright 2015 by Embedded Internet Solutions Inc.,
 * All rights reserved.
 *
 * This software is the confidential and proprietary information
 * of Embedded Internet Solutions Inc.("Confidential Information").  
 * You shall not disclose such Confidential Information and shall 
 * use it only in accordance with the terms of the license agreement 
 * you entered into with Embedded Internet Solutions Inc.
 *
 */

package cn.broadin.app.hotel;


import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.reflect.Method;

import cn.broadin.app.hotel.app.AppConfig;
import cn.broadin.app.hotel.app.AppContext;
import cn.broadin.app.hotel.service.ListenNewVersionService;
import cn.broadin.app.hotel.startWebapp.StartWebView;
import cn.broadin.app.hotel.util.MacAddressHelper;
import cn.broadin.app.hotel.util.UtilFile;
import cn.broadin.app.hotel.util.XHttpProxy;
import cn.broadin.app.hotel.util.XLog;
import cn.broadin.app.hotel.util.XToast;
import cn.broadin.app.hotel.util.XUIHelper;
import cn.broadin.app.hotel.util.XUtils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.TextView;
import android.provider.Settings;

/**
 * 湖南有线UI-欢迎界面
 * 
 * @author long
 * @version 1.0.0
 * @date 2015年12月28日上午10:13:58
 */
public class LoadActivity extends BaseActivity {

	private ImageView mImageView;
	private TextView mTextView;
	
	private boolean checkNetWorkFlag = false;
	private boolean firstStart = true;
	
	public String stbStateUrl;
	public String productInfo = "";
	public String chipsInfo = "";
	private String authResult = "";
	
	public  String macNum = "";
	public static String hotelsIntroUrl; 
	public String HotelUrl;
	public String videoUrl;
	public AppContext appContext = null;
	public static String indexVideoFile = null;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_loading);
		appContext = (AppContext)getApplicationContext();  //获取全局变量app	
		getSystemInfo();
		appContext.setProductInfo(productInfo);
		appContext.setChipsInfo(chipsInfo);
		macNum = MacAddressHelper.getInstance().getMacAddress(this);
		//getIndexVideoPath();
		if(deleteFile()) {
			XLog.d("deleteFile end");
		}
		initView();	
		
		//设置系统的NTP时间服务器地址		
		if (Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED)) {
			String NtpServerFlagDir = "/data/local/";
			String NtpServerFlagFile = "ntpServerFlag.txt";
			File NtpServerFlagfile = new File(NtpServerFlagDir,NtpServerFlagFile);
			if(NtpServerFlagfile.exists() && NtpServerFlagfile.length() != 0) {
				Log.d("dyh--ntpserver-->", "dyhntpserverSet----NOSET");
			} else {
				Log.d("dyh--ntpserver-->", "ntpServerIP = " + AppConfig.mynewntp);
				if(AppConfig.mynewntp != null && !AppConfig.mynewntp.equals("")) {
					Log.d("dyh--ntpserver-->", "SetNtpServer Start");
					Settings.Global.putString(getContentResolver(), "ntp_server", AppConfig.mynewntp);
					String tempContent = "mynewntp = " + AppConfig.mynewntp;
					String dirName = "/data/local/";
					String fileName = "ntpServerFlag.txt";
					if(UtilFile.saveFile(dirName, fileName, tempContent)) {

					}

				}
			}
		}
		
	}
	

	
	private void getSystemInfo() {
		getProductInfo();
		getChipsInfo();
	}
	private void getProductInfo() {
		String product = null;
		String cmd1 = "getprop ro.product.manufacturer";
		try {
			Process process = Runtime.getRuntime().exec(cmd1);
			InputStreamReader ir = new InputStreamReader(process.getInputStream());
			BufferedReader input = new BufferedReader(ir);
			
			while((product = input.readLine()) != null){
				Log.i("DDD",product);
				productInfo = product;
			}

			} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			}
	}
	
	private void getChipsInfo() {
		String chips = null;
		String cmd = "getprop ro.product.name";
		try {
			Process process = Runtime.getRuntime().exec(cmd);
			InputStreamReader ir = new InputStreamReader(process.getInputStream());
			BufferedReader input = new BufferedReader(ir);
			
			while((chips = input.readLine()) != null){
				Log.i("DDD",chips);
				chipsInfo = chips;
			}

			} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			}
	}
	
	

	/**
	 * 界面初始化
	 * 
	 * @author long
	 * @return void
	 * @exception @author
	 *                long
	 * @since 1.0.0
	 * @date 2016年1月4日 下午1:07:33
	 */
	private void initView() {
		DisplayMetrics metric = new DisplayMetrics();
		getWindowManager().getDefaultDisplay().getMetrics(metric);
		int width = metric.widthPixels; // 屏幕宽度（像素）
		int height = metric.heightPixels; // 屏幕高度（像素）
		XLog.i("DisplayMetrics : width => " + width + ", height => " + height);
		float density = metric.density; // 屏幕密度（0.75 / 1.0 / 1.5）
		XLog.i("density : " + density);
		int densityDpi = metric.densityDpi; // 屏幕密度DPI（120 / 160 / 240 / 320）
		XLog.i("densityDpi : " + densityDpi);

		mImageView = (ImageView) this.findViewById(R.id.loading_img);
		mTextView = (TextView) this.findViewById(R.id.loading_text);

		Animation rotate = AnimationUtils.loadAnimation(this, R.anim.loading_rotate);
		mImageView.startAnimation(rotate);
		
		// 检测网络
		/*boolean networkIsOk = XUtils.isNetworkAvailable(LoadActivity.this);
		
		if(networkIsOk){
			Log.d("dyh--networkIsOk-->", "networkIsOk");
			// 设备认证
			mHandler.sendEmptyMessage(NETWORK_OK);
		} else {
			// 启动线程检测， 最大耗时20S
			mTextView.setText("正在尝试建立网络连接");
			new Thread(new checkNetWork()).start();
			
		}*/
		
		new Thread(new networkStatus()).start();
		 
		
	}
	
	public class networkStatus implements Runnable{

		/* （非 Javadoc）
		 * @see java.lang.Runnable#run()
		 */
		@Override
		public void run() {
			// TODO 自动生成的方法存根
			boolean networkIsOk = XUtils.isNetworkAvailable(LoadActivity.this);
			if(networkIsOk){
				Log.d("dyh--networkIsOk-->", "networkIsOk");
				// 设备认证
				mHandler.sendEmptyMessage(NETWORK_OK);
			} else {
				// 启动线程检测， 最大耗时20S
				mTextView.setText("正在尝试建立网络连接");
				
				if(productInfo == null || productInfo.equals("")) {  //再获取一次厂家信息
					productInfo = XUtils.getSystemInfo();
				}
				
				if(productInfo.equals("CNCR")) { // 初灵机顶盒解决方案
					new Thread(new CLcheckNetWork()).start(); 
				} else if(productInfo.equals("MBX") || productInfo.equals("JIUZHOU") || productInfo.equals("Skyworth")) { //九州及智诺达机顶盒解决方案
					new Thread(new checkNetWork()).start();
				} 
				
				else {  //默认处理方式
					new Thread(new checkNetWork()).start(); 	
				}
				
				
			}
		}
		
	}
	

	
	public class checkNetWork implements Runnable{
		
		private long startTimes = 0;
		private long currentTimes = 0;
		
		public checkNetWork(){
			startTimes = System.currentTimeMillis();
			checkNetWorkFlag = true;
		}
		
		public void run() {
			while(checkNetWorkFlag){	
				currentTimes = System.currentTimeMillis();
				if(currentTimes - startTimes > 20000){
					checkNetWorkFlag = false;
					mHandler.sendEmptyMessage(NETWORK_ERROR);
					break;
				}
				
				boolean networkIsOk = XUtils.isNetworkAvailable(LoadActivity.this);
				if(networkIsOk){
					checkNetWorkFlag = false;
					mHandler.sendEmptyMessage(NETWORK_OK);
					break;
				}
				
				try {
					Thread.sleep(500);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		}
	};
	
public class CLcheckNetWork implements Runnable{
		
		private long startTimes = 0;
		private long currentTimes = 0;
		private long conutTimes = 0;
		private boolean S905_Flag = false;
		private boolean S905_check_flag = false;
		
		public CLcheckNetWork(){
			startTimes = System.currentTimeMillis();
			checkNetWorkFlag = true;
		}
		
		//to get s905_prop 
		public String getprop(String key, String defaultValue) {
		    String value = defaultValue;
		    try {
		        Class<?> c = Class.forName("android.os.SystemProperties");
		        Method get = c.getMethod("get", String.class, String.class );
		        value = (String)(   get.invoke(c, key, "unknown" ));
		    } catch (Exception e) {
		        Log.d("check boot", "get property error, " + e.getMessage());
		    }
		    Log.d("check boot", "get property, " + key + " = " + value);
		    return value;
		}
		
		public void run() {		
			while(checkNetWorkFlag) {
				String bootflag = getprop("bootvideo.complete","0");
				if("unknown".equals(bootflag)) {
					S905_Flag =false;
					Log.d("check manufacturers","not cncr s905 box!"+S905_Flag);
				} else if("1".equals(bootflag)) {
					S905_Flag = true;
					S905_check_flag = true;
					Log.d("check boot","is cncr s905 box!"+S905_Flag);
				} else {
					S905_Flag =true;
					S905_check_flag =false;
					Log.d("check boot","is cncr s905 box! now loop check bootflag"+S905_Flag);
				}
				
				startTimes = System.currentTimeMillis();
				if((S905_Flag==false) || (S905_check_flag==true)) {
				while(checkNetWorkFlag) {
				currentTimes = System.currentTimeMillis();
				conutTimes = currentTimes - startTimes;
				Log.d("currentime"+currentTimes, "starttime"+startTimes);				
				Log.d("time_count"+conutTimes,"currentTimes-startTimes");
				if(currentTimes - startTimes > 30000){
				  //if(currentTimes > 30000) {
					checkNetWorkFlag = false;
					mHandler.sendEmptyMessage(NETWORK_ERROR);
					Log.d("timeout", "timeout");
					break;
				}
				
				boolean networkIsOk = XUtils.isNetworkAvailable(LoadActivity.this);
				if(networkIsOk){
					checkNetWorkFlag = false;
					mHandler.sendEmptyMessage(NETWORK_OK);
					Log.d("check net ok","OK");
					break;
				}
				
				try {
					Log.d("net sleep","OK");
					//startTimes = System.currentTimeMillis();
					Thread.sleep(500);
					//conutTimes = System.currentTimeMillis();
					//Log.d("sleep time"+(conutTimes - startTimes),"OK");
					//currentTimes += 1000;
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				}
				}
				else {
					Log.d("check boot","is cncr s905 box! now loop check bootflag+254+"+S905_Flag);
				}
				if((S905_Flag==false) || (S905_check_flag==true)) {
					Log.d("check over","over");
					break;
				}
			}
		}
	};

	private String stbStateUrlFormat(String macNum){
		String pingTempCode = AppConfig.secuCode + macNum;
		String pingsignCode = XUtils.md5(pingTempCode);
		String stbStateUrl = AppConfig.stbStateUrl + macNum + "&sign=" + pingsignCode;
		return stbStateUrl;
	}
	
	private void deviceAuth() {
		String tempCode = AppConfig.secuCode + macNum + AppConfig.versionCode;
		String signCode = XUtils.md5(tempCode);
		XLog.d("tempCode: " + tempCode + ", signCode: " + signCode);
		stbStateUrl = stbStateUrlFormat(macNum);
		XLog.d("stbStateUrl: " + stbStateUrl);
		
		// 开始验证播控平台
		RequestParams requestParams = new RequestParams();
		requestParams.addBodyParameter("macaddr", macNum);
		requestParams.addBodyParameter("ver", AppConfig.versionCode);
		requestParams.addBodyParameter("sign", signCode);
		HttpUtils httpUtils = XHttpProxy.getHttpUtils();
		httpUtils.send(HttpRequest.HttpMethod.POST, AppConfig.roomUrl, requestParams, new RequestCallBack<String>() {

			@Override
			public void onFailure(HttpException e, String msg) {
				authResult = "failed";
				appContext.setAuthFlag(authResult);
				mHandler.sendEmptyMessage(AUTH_ERROR);
			}

			@Override
			public void onSuccess(ResponseInfo<String> responseInfo) {
				try {
					XLog.i("responseInfo.result: " + responseInfo.result);
					JSONObject jsonObject = JSON.parseObject(responseInfo.result);

					String authFlag = jsonObject.getString("msg"); // 酒店房间认证结果码
					HotelUrl = jsonObject.getString("ad_url");
					videoUrl = jsonObject.getString("vad_url");
					appContext.setStartVideoUrl(jsonObject.getString("start_video"));
					appContext.setIndexVideoUrl(videoUrl);
                    appContext.setHotelsIntroUrl(HotelUrl);//酒店介绍入口地址
					if (!TextUtils.isEmpty(authFlag) && authFlag.equals("success")) {
						authResult = "success";
						appContext.setAuthFlag(authResult);
						mHandler.sendEmptyMessage(AUTH_SUCCESS); // 设备授权成功
					} else {
						authResult = "failed";
						appContext.setAuthFlag(authResult);
						mHandler.sendEmptyMessage(AUTH_ERROR);
					}

				} catch (Exception e) {
					e.printStackTrace();
					authResult = "failed";
					appContext.setAuthFlag(authResult);
					mHandler.sendEmptyMessage(AUTH_ERROR);
				}
			}
		});
	}

	private static final int AUTH_SUCCESS = 0; // 认证成功
	private static final int AUTH_ERROR = 1; // 认证失败
	private static final int GOTO_MAIN = 2; // 跳转进入主页面
	private static final int NETWORK_OK = 3;	// 网络链接OK
	private static final int NETWORK_ERROR = 4;	// 网络链接OK
	private static final int OPEN_SETTING_APP = 5;	// 打开系统设置界面
	private static final int GOTO_THIRDAPP = 6;    //进入指定的第三方应用
	private static final int CHECK_BOOT_STATUS = 7; // 检测开机视频是否播放完毕
	private static final int START_SERVICE = 8; // 启动Service
	private static final int INIT_UPDATE = 9; 

	private Handler mHandler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
				case INIT_UPDATE:
					initUpdateInfo.start();
					break;
				case AUTH_SUCCESS:
					
					// 启动bootVideo service
					mTextView.setText("播控平台验证成功");
					mHandler.sendEmptyMessage(START_SERVICE);	
					if(productInfo == null || productInfo.equals("")) {  //再获取一次厂家信息
						productInfo = XUtils.getSystemInfo();
					}
					if( productInfo.equals("MBX")) {  //智诺达S805方案
						mHandler.sendEmptyMessage(CHECK_BOOT_STATUS);	
					} else if (productInfo.equals("CNCR") || productInfo.equals("JIUZHOU") || productInfo.equals("Skyworth")) {  //用于九州和初灵机顶盒方案
						mHandler.sendEmptyMessageDelayed(INIT_UPDATE, 500);
					} 
					
					
					else {   //默认处理方案
						mHandler.sendEmptyMessageDelayed(INIT_UPDATE, 500);
					}
					
					break;
				case AUTH_ERROR:
					mTextView.setText("播控平台验证失败");
					mHandler.sendEmptyMessageDelayed(GOTO_MAIN, 500);
					break;
				case CHECK_BOOT_STATUS:
					
					String status = XUtils.getSystemPro();
					XLog.i("bootanim status: " + status);
					if(status != null && status.equals("stopped")){
						mHandler.sendEmptyMessageDelayed(INIT_UPDATE, 800);
					} else {
						mHandler.sendEmptyMessageDelayed(CHECK_BOOT_STATUS, 800);
					}
					
					break;
					
				case START_SERVICE:
					
					//启动机顶盒状态信息监控服务及bootvideo及升级检测
					Intent mService = new Intent(LoadActivity.this, ListenNewVersionService.class); 
					Bundle stbstatebundle = new Bundle();  
					stbstatebundle.putString("stbStateUrl", stbStateUrl);
					stbstatebundle.putString("fireStateUrl", AppConfig.fireStateUrl);
					stbstatebundle.putString("macNum", macNum);  
					stbstatebundle.putString("chipsInfo", chipsInfo); 
					mService.putExtras(stbstatebundle);
					startService(mService);
					break;
					
				case GOTO_MAIN:
					/*// 此处判断是否已经初始化疏散图数据
					String url = XUtils.getSharedPreferenceConfig(LoadActivity.this, FireActivity.MAP_KEY);
					if(TextUtils.isEmpty(url)){
						
						XUIHelper.openInitActivity(LoadActivity.this);
						finish();
						
					} else {
						XUIHelper.openMainActivity(LoadActivity.this);
						LoadActivity.this.finish();
					}*/

					XUIHelper.openMainActivity(LoadActivity.this);
			    	LoadActivity.this.finish();
					break;
					
				case GOTO_THIRDAPP:					
					try{
						firstStart = false;
						Intent myIntent = new Intent();
						ComponentName mcomp = new ComponentName( "com.hotel.player", "com.hotel.player.PlayerActivity");
						myIntent.setComponent(mcomp);
						myIntent.setAction("android.intent.action.MAIN");
						myIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
						Bundle mbundle = new Bundle();  
						mbundle.putString("authAddress",AppConfig.roomUrl);
						mbundle.putString("versionCode",AppConfig.versionCode);
						myIntent.putExtras(mbundle);
						startActivity(myIntent);
						break;
					}catch(Exception e){
						e.printStackTrace();
						XToast.makeText(LoadActivity.this, "应用启动失败",5000).show();
						mHandler.sendEmptyMessage(GOTO_MAIN);
						break;
					}
				case NETWORK_OK:
					//打开网页应用
				
					mTextView.setText("播控平台验证加载中");
					deviceAuth();
					
					break;
				case NETWORK_ERROR:
					// 跳转进入系统设置界面
					
					XToast.makeText(LoadActivity.this, "网络链接失败,请检查网络", 5000).show();
					
					mHandler.sendEmptyMessageDelayed(OPEN_SETTING_APP, 500);
					break;
				case OPEN_SETTING_APP :				
					firstStart = false;
					Intent mIntent = new Intent();
					ComponentName comp = null;
					if(productInfo == null || productInfo.equals("")) {  //再获取一次厂家信息
						productInfo = XUtils.getSystemInfo();
					}
					if(productInfo.equals("MBX") || productInfo.equals("CNCR")) {  //智诺达和初灵方案系统设置
						 comp = new ComponentName("com.mbx.settingsmbox", "com.mbx.settingsmbox.SettingsMboxActivity");  
					} else if(productInfo.equals("JIUZHOU")) { //九州方案系统设置
						 comp = new ComponentName("com.jzbyapp.jzsettings", "com.jzbyapp.jzsettings.MainActivity");
					}else if(productInfo.equals("Skyworth")) {//创维一体机
						 comp = new ComponentName("com.tianci.setting","com.tianci.setting.TianciSetting");	
					}
					
					else { //默认进入安卓原生系统设置
						 comp = new ComponentName("com.android.settings", "com.android.settings.Settings");
					}
					
					mIntent.setComponent(comp);
					mIntent.setAction("android.intent.action.MAIN");
					mIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
					Bundle mbundle = new Bundle(); 
					mbundle.putString("versionCode", AppConfig.versionCode);
					mbundle.putString("versionDate", AppConfig.versionDate);
					mbundle.putString("versionArea", AppConfig.versionArea);
					mIntent.putExtras(mbundle);
					startActivity(mIntent);
					break;
			}
			super.handleMessage(msg);
		}

		
	};
	
	

	
	String saveDirPath = "";
	
	private void getIndexVideoPath() {
		// TODO 自动生成的方法存根
		XLog.d("indexVideoFile111=productInfo: " + productInfo);
		if(productInfo == null || productInfo.equals("")) {  //再获取一次厂家信息
			productInfo = XUtils.getSystemInfo();
		}
		
		XLog.d("indexVideoFile222=productInfo: " + productInfo);
		if(productInfo.equals("MBX")) {  //智诺达S805方案
			saveDirPath = "/mnt/sdcard";
		} else if(productInfo.equals("CNCR") || productInfo.equals("JIUZHOU") || productInfo.equals("Skyworth")) { //九州和初灵方案
			saveDirPath = "/data/local";
		}
		else {  //默认方案
			saveDirPath = "/data/local";
		}
		
		XLog.d("indexVideoFile333=saveDirPath: " + saveDirPath);
		String tempFilePath = saveDirPath + "/indexVideo";
		String tempFileName = "indexVideo.mp4";
		File file = new File(tempFilePath,tempFileName);
		if(!file.exists() || file.length() == 0) {
			indexVideoFile = videoUrl;
		} else {
			indexVideoFile = saveDirPath + "/indexVideo/indexVideo.mp4";
		}
		
		XLog.d("indexVideoFile444====: " + indexVideoFile);
	}
	
	private void loadUrl(String url) {
		Intent intent = new Intent(this, StartWebView.class);
		intent.putExtra("LoadActivityIn", "true");
		intent.putExtra("indexVideoUrl",videoUrl);
		intent.putExtra("url", url);
		intent.putExtra("data_host", AppConfig.hotelsIntroIP);
		intent.putExtra("data_port", AppConfig.hotelsIntroPort);
		intent.putExtra("macNum", macNum);
		startActivity(intent);
	}
	
	Thread initUpdateInfo = new Thread(new Runnable(){

		@Override
		public void run() {
			// TODO 自动生成的方法存根
			XLog.d("initUpdateInfo: start");
			String tempCode = AppConfig.secuCode + macNum + AppConfig.versionCode;
			String signCode = XUtils.md5(tempCode);
			XLog.d("product = "+productInfo+"tempCode: " + tempCode + ", signCode: " + signCode + ", macNum = " + macNum + "updateapiUrl = " + AppConfig.updateapiUrl + ",chips = " + chipsInfo);
			RequestParams requestParams = new RequestParams();
			requestParams.addBodyParameter("macaddr", macNum);
			requestParams.addBodyParameter("ver", AppConfig.versionCode);
			requestParams.addBodyParameter("product", productInfo);
			requestParams.addBodyParameter("chips", chipsInfo);
			requestParams.addBodyParameter("sign", signCode);
			HttpUtils httpUtils = XHttpProxy.getHttpUtils();
			
			httpUtils.send(HttpRequest.HttpMethod.POST, AppConfig.updateapiUrl, requestParams, new RequestCallBack<String>() {
			
				@Override
				public void onFailure(HttpException e, String msg) {
					
					e.printStackTrace();
					mHandler.sendEmptyMessage(GOTO_MAIN);
					//XToast.makeText(LoadActivity.this, "系统繁忙，请稍后再试！").show();
				}

				@Override
				public void onSuccess(ResponseInfo<String> responseInfo) {
					XLog.i("initUpdateInfo.result: " + responseInfo.result);
					JSONObject jsonObject = JSON.parseObject(responseInfo.result);
					parseUpdateInfo(jsonObject);
				}
			});
		}
		
	});
	private void parseUpdateInfo(JSONObject jsonObject){
		try{
						
			String otaUpadateFlag = jsonObject.getString("upgrade");	// ota系统升级标志
			String update_url = jsonObject.getString("upgrade_url");	// ota系统升级地址
			otaUpdateOnline(otaUpadateFlag, update_url);
		} catch(Exception e){
			e.printStackTrace();
		}
	}
	
	private void otaUpdateOnline(String flag, String url) {
		XLog.d("otaUpdateOnline flag = "+flag+",,,url =  " + url);
		//XToast.makeText(MainActivity.this, url).show();
		if(flag.equals("true")) {
			//先删除掉旧的升级包
			if(deleteFile()) {
				Intent mIntent = new Intent();
				ComponentName comp = new ComponentName( "com.pd.apkinstaller", "com.pd.apkinstaller.MainActivity");
				mIntent.setComponent(comp);
				mIntent.setAction("android.intent.action.MAIN");
				mIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
				Bundle mbundle = new Bundle();  
				mbundle.putString("update_url", url);
				mbundle.putString("productInfo", productInfo);
				mIntent.putExtras(mbundle);
				startActivity(mIntent);	
			} 		
		}else {		
			mHandler.sendEmptyMessage(GOTO_MAIN);
		}
	}
	
	private Boolean deleteFile() {
		XLog.d("deleteFile start");
		Boolean Flag = true;
		File f = new File(AppConfig.OtaFilePath);
		File[] fl = f.listFiles();

		for (int i=0; i<fl.length; i++) {
			XLog.d("dyh---fl = " + fl[i].toString());
			if(fl[i].toString().endsWith(".zip") || fl[i].toString().endsWith(".ZIP"))  
            {  
                if(fl[i].delete())  
                {  
                   Flag = true; 
                }else{  
                   Flag = false;
                }  
            } 
		}

		return Flag;
	}
	
	protected void onDestroy() {
		checkNetWorkFlag = false;
		super.onDestroy();
	};
	
	@Override
	protected void onResume() {
		if(!firstStart){
			mHandler.sendEmptyMessage(GOTO_MAIN);
		}
		super.onResume();
	};
	
}
